package com.cc.demo.controller;

import com.alibaba.fastjson2.JSON;
import com.cc.demo.domain.Basic;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.modifier.Visibility;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.FieldAccessor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;

@RequestMapping("/test")
@RestController
public class TestController {
    @GetMapping("/hello")
    public String hello() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        // 动态创建子类
        Class<? extends Basic> dynamicClass = new ByteBuddy()
                // 指定父类
                .subclass(Basic.class)
                // 添加字段
                .defineField("dynamicField", String.class, Visibility.PRIVATE)

//                .annotateField(AnnotationDescription.Builder.ofType(ExcelProperty.class)
//                        .addAttribute("value", "动态字段")
//                        .build())

                .defineMethod("getDynamicField", String.class, Visibility.PUBLIC)
                .intercept(FieldAccessor.ofField("dynamicField"))
                .make()
                .load(TestController.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded();


        // 通过反射给 dynamicField 赋值
        java.lang.reflect.Field field = dynamicClass.getDeclaredField("dynamicField");
        // 允许访问
        field.setAccessible(true);

        // 实例化动态类
        Basic instance = dynamicClass.getDeclaredConstructor().newInstance();
        instance.setName("test");
        field.set(instance, "dynamicFieldValue");

        // 调用方法（输出被覆盖后的结果）
        return JSON.toJSONString(instance);
    }
}
